package com.ray.juc;

public class ProviderTest {

    /**
     * 生产者消费者
     * 2个生产者生产汉堡，2个消费者消费汉堡
     *
     * 任务用sleep 资源用wait
     */

    public static void main(String[] args) {
        final Data data = new Data();
        new Thread(new Runnable() {
            public void run() {
                for (int i=0;i<30;i++){
                    data.increment();
                }
            }
        },"A").start();
        new Thread(new Runnable() {
            public void run() {
                for (int i=0;i<30;i++){
                    data.decrement();
                }
            }
        },"B").start();
    }
}

class Data{
    private int num=0;//个数

    public synchronized void increment(){
//        while(num!=0){
//            try {
//                this.wait();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
        num++;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.notify();
        System.out.println(Thread.currentThread().getName()+"生产了第"+num+"个汉堡");
    }

    public synchronized void decrement(){
        while(num==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        System.out.println(Thread.currentThread().getName()+"消费了第"+num+"个汉堡");
        num--;
    }
}
